extends Node2D

@export var app_id:String = ""
var request_id: String
# 对话id用于后续调用
var conversation_id: String
signal answer_finished
var new_answer: String
@onready var file_dialog: FileDialog = $"../FileDialog"

# 打开一个txt文件并读取内容
func get_txt(path: String):
	var file = FileAccess.open(path, FileAccess.READ)
	var err = file.get_open_error()
	if (err == OK):
		var line = "#"
		line = file.get_line()
		return line
	else:
		print("Open Error:", err)

func _on_file_dialog_file_selected(path: String) -> void:
	app_id = get_txt(path)
	file_dialog.got_txt.emit()
	print("app_id:%s" % [app_id])

func _ready() -> void:
	var file_dialog = get_parent().get_node("FileDialog")
	if (file_dialog.vi == true):
		await file_dialog.got_txt
	GetConversation()

#region 对话创建请求
# 创建对话请求
func GetConversation():
	# 请求的地址
	var url = "https://qianfan.baidubce.com/v2/app/conversation"
	# 请求体的用户id
	var payload = {
		"app_id": app_id
	}
	# 请求头
	var headers = [
		"Content-Type: application/json",
		"X-Appbuilder-Authorization: Bearer bce-v3/ALTAK-sE4j0EULAuscLk7RjKMHO/e781a22306406a3704badbe1e9c74ff33d1f754b"
	]
	# 发送请求
	$TokenRequest.request(url, headers, HTTPClient.METHOD_POST, JSON.stringify(payload))

# 获得创建对话请求
func _on_token_request_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
	# 检查收到的回复内容
	if response_code == 200:
		var json = JSON.new()
		# 将回复内容转换成json
		var response_json = json.parse(body.get_string_from_utf8())
		if response_json == OK:
			# 如果接收成功
			var data_received = json.data
			conversation_id = data_received["conversation_id"]
			print("新建对话成功,对话id: %s" % [conversation_id])
		else:
			# 接收错误
			print("Error: ", json.get_error_message())
	else:	
		print("Request failed with status code: ", response_code)
#endregion

#region 答案请求
# 创建答案请求
func GetAnswer(query: String):
	var url := "https://qianfan.baidubce.com/v2/app/conversation/runs"
	print('conversation_id:', conversation_id)
	var payload = {
		"app_id" : app_id,	# 应用id
		"query" : query,	# 用户输入的问题
		"stream" : false, 	# 是否以流式接口的形式返回数据，默认false
		"conversation_id" : conversation_id,	# 对话id，可以通过新建对话接口创建
		# 'file_ids' : 类型为list[string] 非必填，如果用户上传了文件才填
	}
	var headers = [
		"Content-Type: application/json",
		"X-Appbuilder-Authorization: Bearer bce-v3/ALTAK-sE4j0EULAuscLk7RjKMHO/e781a22306406a3704badbe1e9c74ff33d1f754b"
	]
	
	$AnswerRequest.request(url, headers, HTTPClient.METHOD_POST, JSON.stringify(payload))

# 对话答案
func _on_answer_request_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
	if response_code == 200:
		var json = JSON.new()
		# 将回复内容转换成json
		var response_json = json.parse(body.get_string_from_utf8())
		if response_json == OK:
			# 如果接收成功
			var data_received = json.data
			new_answer = data_received["answer"]
			print("获得答案,新答案为 %s" % [new_answer])
			answer_finished.emit()
		else:
			# 接收错误
			print("Error: ", json.get_error_message())
	else:
		print("Request failed with status code: ", response_code)
#endregion
